$.storages = window.localStorage;


$(function() {
	/** 关闭panel **/
	$(document.body).on("click", ".x-panel-closable .x-panel-close", function() {
		$(this).closest(".x-panel-closable").hide();
	});
});


$(function() {

	// 图片上传
	// <div class="x-image-upload"><input type="file"/><img /></div>
	var html = '<div class="cannt-preview"><div class="valign-middle-wrap"><div class="valign-middle-box"><div class="valign-middle">浏览器版本过低, 不支持图片预览...</div></div></div></div>';
	$(document.body).on("change", ".x-image-upload input[type=file]", function() {
		if (!this.files) {
			var box = $(this).closest(".x-image-upload").find(".img");
			if (box.find(".cannt-preview").length == 0) { $(html).prependTo(box); }
		} else {
			var file = this.files[0];
			var img = $(this).closest(".x-image-upload").find("img")[0];
			var reader = new FileReader();
			reader.readAsDataURL(file);
			reader.onload = function(e){
				img.src=this.result;
			}
		}
	});
});



(function($) {
	if ($.fn.xcall) { return; }
	$.fn.xcall = function(operate, options) {
		var xcall = this.data("x-call");
		if (xcall) {
			return this.eq(0)[xcall](operate, options);
		} else {
			$.log.error("data x-call not found.");
		}
	};
})(jQuery);


/**
 * ------------------------------
 * baidu template
 * <div class="space">
 *     <div class="content"></div>
 *     <script type="xxx">...</script>
 * </div>
 * ------------------------------
 * var html = $(".space").template("xxx", data);
 * var $content = $(".space").template(".content", "xxx", data); // 将模板内容渲染至content
 * ------------------------------
 */
(function($) {
	var KEY = "BAIDU-TEMPLATE";
	$.fn.template = function(type, json) {
		var selector = undefined;
		if ($.dt.isElement(type) || $.dt.isString(type) && $.dt.isString(json)) {
			selector = type; type = arguments[1]; json = arguments[2];
		}
		var me = $(this);
		var cache = me.data(KEY) || {};
		if (!cache[type]) {
			cache[type] = baidu.template(me.find("script[type='" + type + "']").html());
			me.data(KEY, cache);
		}
		var html = cache[type](json);
		return selector ? me.find(selector).html(html) : html;
	};
})(jQuery);

/*!
 * 全选/全不选, 赵卉华, 2015-02-14
 */
(function($) {
    // 全选/全不选
    // 先根据data-container找到容器(默认为"form, table, body")
    // 再根据data-name或name过滤
    $.fn.selectall = function(fn) {
        return this.each(function() {
            var me = $(this);
            if (!me.is("input[type=checkbox]")) { return true; }
            if (me.is(":disabled")) { return true; }
            var checked = me.is(":checked");
            var container = me.data("container") || "form, table, body";
            var checkbox = me.closest(container).find("input[type=checkbox]:not(:disabled)").not(this);
            var name = me.data("name") || me.attr("name");
            if (name) { checkbox = checkbox.filter("[name='" + name + "']") }
            checkbox.prop("checked", checked);
            fn && fn.call(this, checkbox, checked);
        });
    };
})(jQuery);


(function($) {
	/**
	 * ------------------------------
	 * 根据页面地址获取参数对象
	 * ------------------------------
	 * 示例: http://xxx/x.html?name=zhh&id=100
	 * $.getPageParams() --> { name:"zhh", id:"100" }
	 * $.getPageParams("name") --> "zhh"
	 * $.getPageParams("id") --> "100"
	 * -------------------------------------------------------------
	 * @author 赵卉华
	 * date: 2014-08-12
	 * -------------------------------------------------------------
	 */
	$.getPageParams = function(name) {
		var params = {};
		var string = window.location.search.substr(1);
		if(string) {
			var array = string.split('&');
			$.each(array, function(idx, text){
				var words= text.split('=');
				params[words[0]] = decodeURIComponent(words[1]);
			});
		}
		return name == null ? params : params[name];
	};
})(jQuery);

/** 存放数据(session) **/
(function($) {
	var KEY = "AUTH-PARAMS";
	$.getAuthParams = function(name) {
		var text = $.storages.getItem(KEY);
		var params = JSON.parse(text);
		return name == null ? params : params[name];
	};

	var params = $.getPageParams();
	if (params.first) {
		if (window.WebView && window.WebView.getAuthParams) {
			try {
				var text = window.WebView.getAuthParams();
				$.log.debug("AuthParams --> " + text);
				$.storages.setItem(KEY, text);
			} catch (e) {
				$.log.error("WebView.getAuthParams() error.");
				$.log.debug(e);
			}
		} else if (params.serverUrl) {
			delete params.first;
			var text = JSON.stringify(params);
			$.storages.setItem(KEY, text);
		}
	}
})(jQuery);



(function($) {
	/**
	 * -------------------------------------------------------------<br>
	 * CSS类型<br>
	 * -------------------------------------------------------------<br>
	 * <div class="xxx action-edit"></div><br>
	 * $(".xxx").cssType("action") --> edit<br>
	 * -------------------------------------------------------------<br>
	 * <div class="xxx"></div><br>
	 * $(".xxx").cssType("action", "edit") --> <div class="xxx action-edit"></div><br>
	 * -------------------------------------------------------------<br>
	 * <div class="xxx action-edit"></div><br>
	 * $(".xxx").cssType("action", "delete") --> <div class="xxx action-delete"></div><br>
	 * -------------------------------------------------------------<br>
	 * <div class="xxx action-edit"></div><br>
	 * $(".xxx").cssType("action", "") --> <div class="xxx"></div><br>
	 * -------------------------------------------------------------<br>
	 * @author 赵卉华<br>
	 * date: 2016-08-18<br>
	 * -------------------------------------------------------------<br>
	 */
	$.fn.cssType = function(key, value) {
		var prefix = key + "-";
		if (value == undefined) {
			var css = this.attr("class") || "";
			var array = css.split(/\s+/g);
			for (var i = 0; i < array.length; i++) {
				if (array[i].startsWith(prefix)) {
					return array[i].substring(prefix.length);
				}
			}
			return null;
		} else {
			return this.each(function() {
				var me = $(this);
				var css = me.attr("class") || "";
				var array = css.split(/\s+/g);
				for (var i = 0; i < array.length; i++) {
					if (array[i].startsWith(prefix)) {
						me.removeClass(array[i]);
					}
				}
				if (value.length) {
					me.addClass(prefix + value);
				}
			});
		}
	};
})(jQuery);


(function($) {
	var succ = function(json) {
		return json.code == "SUCCESS";
	};
	var getBaseUrl = function(href) {
		if (/^https?:/.test(href) || href.charAt(0) == '/') {
			return href;
		} else {
			var realHref = href.replace(/[?&#].*$/, "");
			var base = $("meta[name=relative-path]").attr("content");
			if (realHref.endsWith(".json")) { base = $("meta[name=absolute-path]").attr("content"); }
			return base + (href ? (href.startsWith('/') ? href.substring(1) : href) : "");
		}
	};
	var getFullUrl = function(href) {
		if (/^https?:/.test(href)) {
			return href;
		} else {
			var base = $("meta[name=absolute-path]").attr("content");
			return location.origin + base + (href ? (href.startsWith('/') ? href.substring(1) : href) : "");
		}
	};
	var encodeHtml = function (source) {
		return String(source)
			.replace(/&/g,'&amp;')
			.replace(/</g,'&lt;')
			.replace(/>/g,'&gt;')
            .replace(/\\/g,'&#92;')
			.replace(/"/g,'&quot;')
			.replace(/'/g,'&#39;');
	};
	var decodeHtml = function (source) {
		return String(source)
			.replace(/&amp;/g,'&')
			.replace(/&lt;/g,'<')
			.replace(/&gt;/g,'>')
            .replace(/&#92;/g,'\\')
			.replace(/&quot;/g,'"')
			.replace(/&#39;/g,"'");
	};
	// pad("12345", '_', 10)  返回 _____12345
	// pad("12345", '_', false, 10) 返回 12345_____
	var pad = function(string, c, left, length) {
		if ($.dt.isNumber(c)) {
			length = c;
			c = $.dt.isNumber(string) ? '0' : ' ';
			left = true;
		} else if ($.dt.isBoolean(c)) {
			length = left;
			left = c;
			c = $.dt.isNumber(string) ? '0' : ' ';
		} else if ($.dt.isNumber(left)) {
			length = left;
			left = true;
		}
		string = String(string);
		var temp = [];
		for (var i = string.length; i < length; i++) {
			temp.push(c);
		}
		return left ? temp.join("") + string : string + temp.join("");
	};
	// 克隆
	var clone = function(object) {
		if ($.isArray(object)) {
			var array = [];
			$.each(object, function() {
				array.push(clone(this));
			});
			return array;
		} else {
			return $.extend(true, {}, object);
		}
	};
	// baidu template
	// <script type="xxx">...</script>
	// var html = Utils.baidu.template("xxx", data);
	// var $selector = Utils.baidu.template(".selector", "xxx", data); // 将模板内容渲染至selector
	var tpl = {};
	var template = function(type, json) {
		var selector = undefined;
		if ($.dt.isElement(type) || $.dt.isString(type) && $.dt.isString(json)) {
			selector = type; type = arguments[1]; json = arguments[2];
		}
		if (!tpl[type]) {
			tpl[type] = baidu.template($("script[type=" + type + "]").html());
		}
		var html = tpl[type](json);
		return selector ? $(selector).html(html) : html;
	};
	var newlineToParagraph = function(text) {
		var trimed = $.trim(text);
		if (trimed.startsWith("<") && trimed.endsWith(">")) {
			return text;
		} else {
			return ("<p>" + text.replace(/\r?\n/g, "</p><p>") + "</p>").replace(/<p><\/p>/ig, "<p>&nbsp;</p>");
		}
	};
	var enterToNext = function(inputs, fn) {
		inputs.keydown(function(e) {
			var self = this;
			var me = $(this);
			if (e.keyCode == 13) {
				e.preventDefault();
				var index = inputs.index(this);
				if (index == inputs.length - 1) {
					fn && fn.call(this, e);
				} else {
					var input = null;
					inputs.each(function(i) {
						if (self == this) {
							input = inputs.get(i + 1);
						}
					})
					input && input.focus();
				}
			}
		});
	};

	// assets/libs/sockjs/dist/sockjs.min.js
	// assets/libs/stomp-websocket/2.3.3/stomp.js
	// Utils.websocket.subscribe('/topic/xxx', fn);
	var websocket = (function() {
		var client = null;
		var subscribes = []; // { topic, fn }
		var connect = function(options) {
			if (client && client.ws.readyState === SockJS.CONNECTING) { // 正在连接
				// 什么也不干, 等待连接成功
			} else if (client && client.connected) {
				// 已经连接成功, 什么也不干
			} else {
				client = Stomp.over(new SockJS(Utils.getBaseUrl('sockjs')));
				client.connect(options, function() {
					$.each(subscribes, function(i, v) {
						client.subscribe(v.topic, function(text) { parse(text, v.fn); });
					});
				});
			}
		};
		var subscribe = function(topic, fn) {
			subscribes.push({ topic:topic, fn:fn });
			if (client && client.ws.readyState === SockJS.CONNECTING) { // 正在连接
				// 什么也不干, 等待连接成功
			} else if (client && client.connected) {
				client.subscribe(topic, function(text) { parse(text, fn); });
			} else {
				connect({});
			}
		};
		var disconnect = function() {
			if (client && client.connected) {
				client.disconnect();
			}
		};
		var parse = function(frame, fn) {
			var text = frame.body;
			var parsed = text;
			if (text && $.dt.isString(text) && text.startsWith("{")) {
				try {
					parsed = JSON.parse(text);
					if (parsed.extra) {
						parsed.extra.topic = frame.headers && frame.headers.destination;
					}
				} catch (e) {
				}
			}
			if ($.isFunction(fn)) {
				fn(parsed);
			} else if ($.isPlainObject(fn)) {
				var succ = Utils.succ(parsed);
				if (succ && fn.succ) {
					fn.succ(parsed);
				} else if (!succ && fn.fail) {
					fn.fail(parsed);
				}
			}
		};
		return {
			connect: connect,
			subscribe: subscribe,
			disconnect: disconnect
		};
	})();

	if (!window.Utils) { window.Utils = {}; }
	$.extend(window.Utils, {
		websocket: websocket,
		clone:clone, succ:succ, 
		pad:pad,
		getBaseUrl:getBaseUrl, getFullUrl:getFullUrl,
		encodeHtml:encodeHtml, decodeHtml:decodeHtml,
		newlineToParagraph:newlineToParagraph,
		enterToNext:enterToNext,
		warnTips: function(msg) { $.log.debug("[WARN]" + msg); },
		succTips: function(msg) { $.log.debug("[SUCC]" + msg); },
		showLoading: function() { $.log.debug("show loading..."); },
		stopLoading: function() { $.log.debug("stop loading..."); },
		baidu:{template:template}
	});
})(jQuery);
